const Service = require('egg').Service;
class TopicsService extends Service {

  async index(data) {

    const { ctx } = this;
    const { page, pageSize } = data;

    delete data.page;
    delete data.pageSize;

    const obj = {
      limit: pageSize,
      offset: (page - 1) * pageSize,
      where: data,
    };

    const { count, rows } = await ctx.model.Topics.findAndCountAll(obj);

    return {
      count,
      rows,
      page,
      pageSize,
    };
  }

  async create(data) {
    const MODEL = await this.ctx.model.Topics.create(data);
    await MODEL.save();


    return MODEL.id;
  }

  async update(id, data) {

    const model = await this.ctx.model.Topics.findOne({ where: { id } });
    if (model) {
      const temp = await this.ctx.model.Topics.update(data, {
        where: { id },
        returning: true,
        // plain: true,
      });
      return temp[1];
    }
    return null;

  }

  async destroy(id) {

    const i = await this.ctx.model.Topics.destroy({ where: {
      id,
    } });

    return i;
  }


  async show(id) {
    const model = await this.ctx.model.Topics.findOne({ where: {
      id,
    } });

    return model;
  }

}

module.exports = TopicsService;
